import axios from "axios";
import { fetchEventSource } from "@microsoft/fetch-event-source";
import { ref, toRaw, reactive, watch } from "vue";
import getURL from "@/utils/http/address";

import {
  SysFunction,
  dataTools,
  webTools,
  Knotools,
  drawTools
} from "./FunctionList";
const myscrollRef = ref();
let ctrl: AbortController;
let tools = webTools;
const msg_content = ref();
const showLoading = ref(false); //数据是否加载
const MessageList = reactive([]); //消息列表
const isTools = ref(false);
const funArr = ref();
const imageURL = ref();
const AIModel = ref("1");
const AIModelName = ref("glm-4-flash");
const { callFunction } = SysFunction();
const myObj = ref();
const aiConfig = ref();
const newDD = ref();
//访问普通模型
const AIhttp = data => {
  ctrl = new AbortController();
  const BodyJSON = {
    model: AIModelName.value,
    messages: toRaw(data),
    stream: true,
    tools: tools,
    stop: ["my_stop"],
    tool_choice: "auto"
  };
  console.log(BodyJSON);
  //https://open.bigmodel.cn/api/paas/v4/chat/completions
  fetchEventSource(aiConfig.value.gmlURL, {
    method: "POST",
    headers: {
      Authorization: "Bearer " + aiConfig.value.APIKey,
      "Content-Type": "application/json"
    },
    body: JSON.stringify(BodyJSON),
    openWhenHidden: true,
    signal: ctrl.signal,
    onmessage(msg) {
      showLoading.value = false;
      const res: any = JSON.parse(msg.data);
      const mymessage = res.choices[0].delta.content;
      const tool_calls = res.choices[0].delta.tool_calls;

      if (typeof tool_calls != "undefined") {
        const oneTool = tool_calls[0];
        ctrl.abort();

        MessageList.push({
          role: "assistant",
          tool_calls: tool_calls
        });

        callFunction(
          oneTool.function.name,
          oneTool.function.arguments,
          oneTool
        );

        return;
      }

      const finish = res.choices[0].finish_reason;
      if (typeof finish != "undefined") {
        ctrl.abort();
        if (msg_content.value != "") {
          MessageList.push({
            role: "assistant",
            content: msg_content.value
          });
        }
      } else {
        msg_content.value += mymessage;
      }
    }
  });
};

//访问绘图模型
const AIImage = async (data, tools) => {
  //https://open.bigmodel.cn/api/paas/v4/images/generations
  const response = await axios.post(
    aiConfig.value.cogVieURL,
    {
      model: "cogview-3",
      prompt: data
    },
    {
      headers: {
        Authorization: "Bearer " + aiConfig.value.APIKey,
        "Content-Type": "application/json"
      }
    }
  );
  msg_content.value =
    '<img src="' + response.data.data[0].url + '" style="width:80%;"/>';
  //console.log("我是在绘画了。");
  MessageList.push({
    role: "tool",
    //content: response.data.data[0].url,
    content: "生成成功，图片已显示给用户，不需要再次提示。",
    tool_call_id: tools.id
  });
  AIhttp(MessageList);
  console.log("response", response.data.data[0].url);
};
watch(AIModel, () => {
  switch (AIModel.value) {
    case "1":
      tools = webTools;
      AIModelName.value = "glm-4-flash";
      sysInit("webMode");
      console.log("网络达人模式");
      break;
    case "2":
      tools = Knotools;

      AIModelName.value = "glm-4-flash";
      sysInit("knoMode");
      console.log("智多星模式");
      break;
    case "3":
      tools = dataTools;
      AIModelName.value = "glm-4";
      sysInit("dataMode");
      console.log("数据专家模式");
      break;
    case "4":
      tools = drawTools;
      AIModelName.value = "glm-4-flash";
      sysInit("drawMode");
      console.log("绘画达人");
      break;
    case "5":
      tools = webTools;
      AIModelName.value = "glm-4-flash";
      sysInit("textModel");
      console.log("文本专家");
      break;
  }
  console.log();
});

const sysInit = (modeName: string) => {
  //let newDD;
  let sysMsg;
  switch (modeName) {
    case "webMode":
      sysMsg = aiConfig.value.webMode;
      break;
    case "knoMode":
      sysMsg = aiConfig.value.knoMode;
      break;
    case "dataMode":
      sysMsg = aiConfig.value.dataMode;
      break;
    case "drawMode":
      sysMsg = aiConfig.value.drawMode;
      break;
    case "textModel":
      sysMsg = aiConfig.value.textModel;
      break;
    default:
      sysMsg = aiConfig.value.webMode;
      break;
  }
  MessageList.length = 0;
  myscrollRef.value.innerHTML = "";
  console.log(sysMsg, sysMsg);
  MessageList.push({
    role: "system",
    content: sysMsg
  });

  MessageList.push({
    role: "user",
    content: aiConfig.value.aiFirstUserMsg
  });

  newDD.value = document.createElement("div");
  newDD.value.className = "RonHead";
  newDD.value.innerHTML =
    "<img src='" +
    getURL +
    aiConfig.value.aiHead +
    "'/><span>" +
    aiConfig.value.aiName +
    "</span>";
  myscrollRef.value.appendChild(newDD.value);
  showLoading.value = true;

  AIhttp(MessageList);
  msg_content.value = "";
  newDD.value = document.createElement("div");
  myscrollRef.value.appendChild(newDD.value);
};

export {
  AIhttp,
  showLoading,
  msg_content,
  MessageList,
  isTools,
  funArr,
  AIImage,
  imageURL,
  AIModel,
  aiConfig,
  myObj,
  sysInit,
  newDD,
  myscrollRef
};
